package com.tao.china.common.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

import com.tao.china.common.http.porxy.PorxyEntry;

public class HttpClientUtil {
    
    private static final Logger log = Logger.getLogger(HttpClientUtil.class);
    private static final int READ_TIMEOUT = 10000;// 10s
    private static final int CONNECTION_TIMEOUT = 5000; // 10s

    /**
     * 使用get方式发送请求
     * 
     * @param url
     *            要访问的url
     * @return
     * @throws IOException
     * @throws HttpException
     */
    public static final String getMethodHttpClient(String url,
                NameValuePair[] nameValuePairs) throws HttpException, IOException {
            HttpClient httpClient = new HttpClient();
            GetMethod method = null;
            String backUrl = null;
            try {
    
                if (null != nameValuePairs && nameValuePairs.length > 0) {
                    method = new GetMethod(url);
                    method.setQueryString(nameValuePairs);
                    HttpConnectionManagerParams managerParams = httpClient
                            .getHttpConnectionManager().getParams();
                    // 设置连接超时时间(单位毫秒)
                    managerParams.setConnectionTimeout(30000);
                    // 设置读数据超时时间(单位毫秒)
                    managerParams.setSoTimeout(60000);
                    // 打印服务器返回的状态
                    log.info("QueryString--->" + method.getQueryString());
                    int statusCode = httpClient.executeMethod(method);
                    log.info("statusCode--->" + statusCode);
                    if (statusCode == HttpStatus.SC_OK) {
                        // 打印返回的信息
                        backUrl = method.getResponseBodyAsString();
                        log.info("backUrl--->" + backUrl);
                    }
                }
    
            } catch (HttpException hx) {
                log.error("httpConnection.....", hx);
            } catch (IOException ie) {
                log.error("IOException....", ie);
            } finally { // 释放连接
                method.releaseConnection();
            }
            return backUrl;
        }

    public static final String getWithBackStream(final String url, String charset) {
            HttpClient client = new HttpClient();
            GetMethod method1 = new GetMethod(url);
            String response = null;
    
            if (null != url && url.startsWith("http")) {
    
                // 设置请求的编码方式
                if (null != charset) {
                    method1.addRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=" + charset);
                } else {
                    method1.addRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=" + "utf-8");
                }
                int statusCode;
                try {
                    statusCode = client.executeMethod(method1);
    
                    if (statusCode != HttpStatus.SC_OK) {// 打印服务器返回的状态
                        System.out.println("Method failed: "
                                + method1.getStatusLine());
                    }
                    // 返回响应消息
                    byte[] responseBody = method1.getResponseBodyAsString()
                            .getBytes(method1.getResponseCharSet());
                    // 在返回响应消息使用编码(utf-8或gb2312)
                    response = new String(responseBody, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    log.error("UnsupportedEncodingException" + e);
                } catch (HttpException e) {
                    log.error("HttpException" + e);
                } catch (IOException e) {
                    log.error("IOException" + e);
                    System.out.println("------------------response:" + response);
                } finally {// 释放连接
                    method1.releaseConnection();
                }
            }
            return response;

    }

    /**
     * 使用get方式发送请求
     * 
     * @param url
     *            要访问的url
     * @return
     * @throws IOException
     * @throws HttpException
     */
    public static final Map<String, String> getHttpClientXML(String url) throws HttpException, IOException {

        HttpClient httpClient = new HttpClient();
        HttpMethod method = null;
        String backXml = null;
        Map<String, String> backMap = null;
        try {
            method = new GetMethod(url);
            httpClient.executeMethod(method);
            HttpConnectionManagerParams managerParams = httpClient
                    .getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(30000);
            // 设置读数据超时时间(单位毫秒)
            managerParams.setSoTimeout(60000);
            // 打印服务器返回的状态
            System.out.println(method.getStatusLine());
            // 打印返回的信息
            backXml = method.getResponseBodyAsString();
            backMap = new HashMap<String, String>();
            backMap.put("backXml", backXml);
        } catch (HttpException hx) {
            log.error("httpConnection.....", hx);
        } catch (IOException ie) {
            log.error("IOException....", ie);
        } finally { // 释放连接
            method.releaseConnection();
        }
        return backMap;
    }
    
    public static final boolean statusCodeIsOk(String submitUrl,PorxyEntry porxy,int timeout) {
        HttpClient client = new HttpClient();
        if( null != porxy ){
          //代理
            client.getHostConfiguration().setProxy(porxy.getIp(), porxy.getPort());
        }
        try {
            PostMethod post = new PostMethod(submitUrl);
            //解决乱码问题
            post.getParams().setContentCharset("UTF-8");
            // 使用POST方式提交数据
            HttpMethod method = post;
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(10, false));
            //连接的timeout
            client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
            //读取的timeout
            client.getParams().setSoTimeout(READ_TIMEOUT);
            int statusCode = client.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                return true;
            }
        } catch (HttpException e) {
            if (log.isInfoEnabled()) {
                log.error(e);
            }
            return false;
        } catch (IOException e) {
            if (log.isInfoEnabled()) {
                log.error(e);
            }
            return false;
        }
        return false;
    }    

    // 简单post方式发送请求
    public static final byte[] postSimpleMethodHttpClent(String submitUrl, Map<String, String> ParameterMap, PorxyEntry porxy) {
        HttpClient client = new HttpClient();
        if( null != porxy ){
          //代理
            client.getHostConfiguration().setProxy(porxy.getIp(), porxy.getPort());
        }
        byte[] responseBody = null;
        try {
            // 使用POST方式提交数据
            HttpMethod method = getPostMethod(ParameterMap, submitUrl);
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(10, false));
            //连接timeout
            client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
            //读取timeout
            client.getParams().setSoTimeout(READ_TIMEOUT);
            int statusCode = client.executeMethod(method);
            /*
             * changed by jack1_yang responseBody = method.getResponseBody();
             */
            if (statusCode == HttpStatus.SC_OK) {
                responseBody = method.getResponseBody();
            }
        } catch (HttpException e) {
            if (log.isInfoEnabled()) {
                log.error(e);
            }
        } catch (IOException e) {
            if (log.isInfoEnabled()) {
                log.error(e);
            }
        }
        return responseBody;
    }

    private static HttpMethod getPostMethod(Map<String, String> ParameterMap,
            String submitUrl) {
        HttpClientUtil hcUtil = new HttpClientUtil();
        NameValuePair[] data = hcUtil.Map2Pair(ParameterMap);
        PostMethod post = new PostMethod(submitUrl);
        //解决乱码问题
        post.getParams().setContentCharset("UTF-8");
        if (null != data) {
            post.setRequestBody(data);
        }
        return post;
    }

    private NameValuePair[] Map2Pair(Map<String, String> ParametersMap) {
        int size = ParametersMap.size();
        NameValuePair[] data;
        if (size > 0) {
            data = new NameValuePair[size];
        } else {
            return null;
        }
        NameValuePair nameValuePair = null;
        int i = 0;
        for (Object key : ParametersMap.keySet()) {
            nameValuePair = new NameValuePair(String.valueOf(key),
                    String.valueOf(ParametersMap.get(key)));
            data[i] = nameValuePair;
            System.out.println("-->" + String.valueOf(key) + "****"
                    + String.valueOf(ParametersMap.get(key)) + "<--");
            i++;
        }
        return data;
    }
    
    
    public void clientPostTest(){}
    
    public static void main(String args[])
    {
       
//        System.out.println("result:"+statusCodeIsOk("http://openapi.baidu.com/public/2.0/bmt/translate",null,5000));
        //增加测试、代理IP http调用
        String userName = "liusuper2088@163.com";
        
        String passWord = "156456";
        /** 想要提取的HTTP代理数**/
        int total = 1;
         String url = "http://www.dqwu.info/api.php?action=get_proxy&username="+userName+"&password="+passWord+"&total="+total+"&filter=on&nation=on";
         System.out.println( HttpClientUtil.getWithBackStream(url, "utf-8") );
        
    }

}